Home:ALL Converter>How to sanitize allocated memory in C before using free function?

How to sanitize allocated memory in C before using free function?

Ask Time:2021-09-14T14:11:07         Author:Emre Kilic

Json Formatter

I have created a nested struct called employee. I allocate a space for an employee from heap using malloc. Then, I release the space using free. As far as I know, free function only marks a location available for the future allocation. Hence, the content of allocated memory remains in the memory and it causes heap inspection.

Structs I defined in the beginning of my program as follow.

struct address{
    char *city;
    int zip;
}

struct employee{
    char *name;
    struct address add;
}

I implemented a function called sanitize to replace the private fields with junk values (0xAA in this case). Then, I tested sanitize in the main function.

void sanitize(char *ptr, int size){
    memset(ptr, 0xAA, size);
}

int main()
{
    struct employee* emp;
    emp = malloc(sizeof(char) * 40);
    emp->name = "John";
    emp->add.city = "London";
    emp->add.zip = 221;
    printf("%s\n", emp->add.city);
    sanitize(&(emp->add), sizeof(struct address));
    printf("%s\n", emp->add.city);
    return 0;
}

During runtime I get segmentation fault. What is wrong with my program? How and in which order shoul I sanitize nested structs?

Thanks in advance.

Author:Emre Kilic,eproduced under the CC 4.0 BY-SA copyright license with a link to the original source and this disclaimer.
Link to original article:https://stackoverflow.com/questions/69172604/how-to-sanitize-allocated-memory-in-c-before-using-free-function
yy